class FindNumScene extends Scene {
    private stageW: number;
    private stageH: number;
    private timer: egret.Timer;
    private boxArr: Array<object>;
    private currentNum: number = 1;
    private totalNum: number;
    private soundRight: egret.Sound;
    private soundWrong: egret.Sound;
    private soundWin: egret.Sound;
    private timerText: egret.BitmapText;
    private numFont: egret.BitmapFont;

    public constructor() {
        super();
        this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.click, this);
        this.addEventListener(Events.ResourceLoadReady, this.created, this);
        this.init('FindNumSceneSkin', ['findNum']);
    }


    private async created() {
        this.loadSound();
        this.addToStage();
    }


    private loadSound(): void {
        RES.getResByUrl("resource/assets/Font/timer.fnt", this.initTimer, this, RES.ResourceItem.TYPE_FONT);
        RES.getResByUrl("resource/assets/Font/num.fnt", this.numFontReady, this, RES.ResourceItem.TYPE_FONT);
        const soundRight: egret.Sound = this.soundRight = new egret.Sound();
        const soundWrong: egret.Sound = this.soundWrong = new egret.Sound();
        const soundWin: egret.Sound = this.soundWin = new egret.Sound();
        soundRight.load("resource/sounds/score.mp3");
        soundWrong.load("resource/sounds/wrong.mp3");
        soundWin.load("resource/sounds/win.mp3");
    }

    private addToStage() {
        const { stageWidth, stageHeight } = this.stage;
        this.stageW = stageWidth;
        this.stageH = stageHeight;

        const bg = createBitmapByName("bg03_png");
        bg.width = stageWidth;
        bg.height = stageHeight;
        bg.x = 0;
        bg.y = 0;
        this.addToMain(bg);

        const bgLayer = new egret.Shape();
        bgLayer.graphics.beginFill(ColorBlack, 0.7);
        bgLayer.graphics.drawRect(0, 0, stageWidth, stageHeight);
        bgLayer.graphics.endFill();
        this.addToBack(bgLayer);
        drawBackBtn(this.frontLayer, Dispatcher.showMain);
    }

    private start() {
        this.cleanMain();
        const len = 5;
        const totalNum = Math.pow(len, 2);
        this.currentNum = 1;
        this.totalNum = totalNum;
        const numArr = getNumArr(totalNum);
        this.drawNumBox(len, numArr);
    }

    private drawNumBox(len, numArr) {
        const boxArr = [];
        const { stageW, stageH } = this;
        const gapW = 10;
        const gapH = 10;
        const halfGapW = gapW / 2;
        const halfGapH = gapH / 2;
        const boxTotalW = stageW - 4 * SizePw;
        const boxW = (boxTotalW - (len - 1) * gapW) / len;
        const boxFromY = (stageH - (boxW + gapW) * len) * 0.4;
        const fromX = 2 * SizePw;

        numArr.map((num, i) => {
            const val = num + 1;
            const n = i + 1;
            const cn = (n - 1) % len + 1;
            const rn = Math.ceil(n / len);
            const x = fromX + (cn - 1) * (boxW + gapW);
            const y = boxFromY + (rn - 1) * (boxW + gapH);
            const fx = x - halfGapW;
            const tx = x + boxW + halfGapW;
            const fy = y - halfGapH;
            const ty = y + boxW + halfGapH;
            const box = new egret.Shape();
            box.graphics.lineStyle(3, ColorShanLan);
            box.graphics.beginFill(ColorWhite, 0.5);
            box.graphics.drawRoundRect(x, y, boxW, boxW, 20, 20);
            box.graphics.endFill();
            this.addToMain(box);

            boxArr.push({ box, i, n: val, x, y, w: boxW, h: boxW, fx, tx, fy, ty, flag: 0 });

            // const text = new egret.TextField();
            // text.x = x;
            // text.y = y;
            // text.size = boxW * 0.75;
            // text.bold = true;
            // text.italic = true;
            // text.width = boxW;
            // text.height = boxW;
            // text.text = val;
            // text.textAlign = egret.HorizontalAlign.CENTER;
            // text.verticalAlign = egret.VerticalAlign.MIDDLE;
            // text.textColor = ColorBlack;
            // this.addToMain(text);

            const bText = new egret.BitmapText();
            bText.font = this.numFont;
            bText.x = x;
            bText.y = y;
            bText.width = boxW;
            bText.height = boxW;
            bText.text = val;
            bText.textAlign = egret.HorizontalAlign.CENTER;
            bText.verticalAlign = egret.VerticalAlign.MIDDLE;
            this.addToMain(bText);
        });

        this.boxArr = boxArr;
    }

    private initTimer(font: egret.BitmapFont) {
        if (this.timer) {
            this.timer.reset();
        } else {
            const timer = new egret.Timer(100, 0);
            timer.addEventListener(egret.TimerEvent.TIMER, this.drawTimerLabel, this);
            this.timer = timer;
            this.timerText = new egret.BitmapText();
            this.timerText.font = font;
            this.timerText.width = this.stageW;
            this.timerText.x = 0;
            this.timerText.y = 34;
            this.timerText.text = '0秒';
            this.timerText.textAlign = egret.HorizontalAlign.CENTER;
        }
        this.start();
        this.addToMain(this.timerText);
    }

    private numFontReady(font: egret.BitmapFont) {
        this.numFont = font;
    }

    private startTimer() {
        this.timer.start();
    }

    private drawTimerLabel(evt: egret.TimerEvent): void {
        const timer = (evt.target).currentCount;
        this.timerText.text = (timer / 10).toFixed(1) + '秒';
    }

    private stopTimer() {
        this.timer.stop();
    }

    private getHitOne(mx: number, my: number) {
        let hitOne = null;
        const { boxArr } = this;
        for (let k in boxArr) {
            const boxData = boxArr[k];
            const isInX = mx >= boxData['fx'] && mx <= boxData['tx'];
            const isInY = my >= boxData['fy'] && my <= boxData['ty'];
            if (isInX && isInY) {
                if (boxData['flag'] === 0) {
                    hitOne = boxData['i'];
                }
                break;
            }
        }
        return hitOne;
    }

    private click(evt: egret.TouchEvent) {
        const hitOne = this.getHitOne(evt.stageX, evt.stageY);
        if (hitOne !== null) {
            if (this.currentNum === 1) {
                this.startTimer();
            }
            const { boxArr } = this;
            const boxData = boxArr[hitOne];
            if (boxData['flag'] !== 1) {
                const box: egret.Shape = boxData['box'];
                box.graphics.clear();
                if (boxData['n'] === this.currentNum) {
                    box.graphics.beginFill(ColorGreen, 0.5);
                    if (this.totalNum === this.currentNum) {
                        this.stopTimer();
                        this.soundWin.play(0, 1);
                        const winComp = new WinComponent(() => {
                            this.removeChild(winComp);
                            this.start();
                        });
                        this.addToMain(winComp);
                    }
                    boxData['flag'] = 1;
                    this.currentNum = this.currentNum + 1;
                    this.soundRight.play(0, 1);
                } else {
                    box.graphics.beginFill(ColorRed, 0.5);
                    this.soundWrong.play(0, 1);
                }
                box.graphics.drawRoundRect(boxData['x'], boxData['y'], boxData['w'], boxData['h'], 20, 20);
                box.graphics.endFill();
            }
        }
    }
}
